package cs419.magnusmi.trackitcs;

import android.content.Intent;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import org.json.JSONException;


/**
 * Created by Mikael Magnuson on 2/12/14.
 */

public class LogIn extends Activity{

    private UserLoginTask mAuthTask = null;


    // Values for email and password at the time of the login attempt.
    private String user;
    private String pass;


    // UI references.
    private EditText unamePrompt;
    private EditText passwordPrompt;
    private View mLoginFormView;
    private View mLoginStatusView;
    private TextView mLoginStatusMessageView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_log_in);
        setupActionBar();

        // Set up the login form.
        unamePrompt = (EditText) findViewById(R.id.unamePrompt);
        passwordPrompt = (EditText) findViewById(R.id.password);

        mLoginFormView = findViewById(R.id.signup_form);
        mLoginStatusView = findViewById(R.id.login_status);
        mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

        findViewById(R.id.loginBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                    // Launching Sign Up Activity
                    attemptLogin();

            }
        });
    }

    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setupActionBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            // Show the Up button in the action bar.
            getActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    public void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }

        unamePrompt.setError(null);
        passwordPrompt.setError(null);

        user = unamePrompt.getText().toString();
        pass = passwordPrompt.getText().toString();

            boolean cancel = false;
            View focusView = null;


            // Check for a valid password.
            if (TextUtils.isEmpty(user)) {
                unamePrompt.setError(getString(R.string.error_field_required));
                cancel = true;
                focusView = unamePrompt;
            }
            if (TextUtils.isEmpty(pass)) {
                passwordPrompt.setError(getString(R.string.error_field_required));
                focusView = passwordPrompt;
                cancel = true;
            } else if (pass.length() < 6) {
                passwordPrompt.setError(getString(R.string.error_invalid_password));
                focusView = passwordPrompt;
                cancel = true;
            }

            if (cancel) {
                // There was an error; don't attempt login and focus the first
                // form field with an error.
                focusView.requestFocus();
            } else {
                // Show a progress spinner, and kick off a background task to
                // perform the user login attempt.
                mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
                showProgress(true);
                mAuthTask = new UserLoginTask();
                mAuthTask.execute((Void) null);
            }
        }


        /**
         * Shows the progress UI and hides the login form.
         */
        @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
        private void showProgress(final boolean show) {
            // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
            // for very easy animations. If available, use these APIs to fade-in
            // the progress spinner.
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
                int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

                mLoginStatusView.setVisibility(View.VISIBLE);
                mLoginStatusView.animate()
                        .setDuration(shortAnimTime)
                        .alpha(show ? 1 : 0)
                        .setListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
                            }
                        });

                mLoginFormView.setVisibility(View.VISIBLE);
                mLoginFormView.animate()
                        .setDuration(shortAnimTime)
                        .alpha(show ? 0 : 1)
                        .setListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                            }
                        });
            } else {
                // The ViewPropertyAnimator APIs are not available, so simply show
                // and hide the relevant UI components.
                mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
                mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            }
        }




/**
 * Represents an asynchronous login/registration task used to authenticate
 * the user.
 */
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
    private String response = "";
    private boolean errors = true;
    String API = "";

    /**
     * method to perform login in background
     * @param params none
     * @return errors or not
     */
    @Override
    protected Boolean doInBackground(Void... params) {

        //DEBUG System.out.println("login started");

        //PHP to login
        String register = "http://web.engr.oregonstate.edu/~cohenad/cs419/index.php/login";

        //create array for http
        JSONParser jsonParser = new JSONParser();
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("user", user));
        parameters.add(new BasicNameValuePair("pass", pass));

        //perform http POST
        JSONObject json = jsonParser.makeHttpRequest(register, "POST", parameters);

        try{
            response = json.getString("message");
            errors = json.getBoolean("error");
            API = json.getString("API");
        }
        catch (JSONException e) {
            errors = false;
        }

        //DEBUG System.out.println("login done");
        return errors;
    }

    /**
     * post login method to indicate results and perform navigation
     * @param errors
     */
    @Override
    protected void onPostExecute(final Boolean errors) {
        mAuthTask = null;
        showProgress(false);
        boolean success = !errors;  // no login errors = success
        //DEBUG System.out.println("login done2");


        if (success) {
            //if successful, go to inventory, passing API key with intent for session use
            Context context = getApplicationContext();
            Intent goInventory = new Intent(context, Inventory.class);
            Utility.addToIntent(goInventory, user, API);
            startActivity(goInventory);

        }

            //if invalid credentials, return back to sign in.
            else {
            Context context = getApplicationContext();
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, response, duration);
            toast.show();
            //finish();
            }
        }


    /**
     * Resetter function for invalid credentials.
     */
    @Override
    protected void onCancelled() {
        mAuthTask = null;
        showProgress(false);
    }
}
}


